package com.dsteiner.xelavos.client.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;

import com.dsteiner.widgets.client.DateUtilImpl;
import com.dsteiner.widgets.client.IJsUtil;
import com.dsteiner.widgets.client.JsUtil;
import com.dsteiner.widgets.client.StringUtil;
import com.dsteiner.widgets.client.Widgets.ILazyWidget;
import com.dsteiner.widgets.client.Widgets.IWidget;
import com.dsteiner.widgets.client.Widgets.WidgetListenerAdapter;
import com.dsteiner.widgets.client.domain.ModelObject;
import com.dsteiner.widgets.client.domain.Sort;
import com.dsteiner.widgets.client.model.PrefilledTextBoxModel;
import com.dsteiner.widgets.client.model.SuggestBoxModel;
import com.dsteiner.widgets.client.model.SuggestionModel;
import com.dsteiner.widgets.client.rpc.SearchResult;
import com.dsteiner.widgets.client.rpc.SearchRequest.SearchRequestImpl;
import com.dsteiner.xelavos.client.constants.Constants;
import com.dsteiner.xelavos.client.domain.Job;
import com.dsteiner.xelavos.client.model.CreateObjectModel;
import com.dsteiner.xelavos.client.rpc.DataService;
import com.google.appengine.api.datastore.Text;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class CreateJobController implements IModelObjectBuilder{

	private PrefilledTextBoxModel descriptionTextBoxModel;
	private PrefilledTextBoxModel nameTextBoxModel;
	private PrefilledTextBoxModel empleadorTextBoxModel;
	private PrefilledTextBoxModel contactTextBoxModel;
	private CreateObjectModel createObjectModel;
	private PrefilledTextBoxModel validUntilTextBoxModel;
	private IJsUtil jsUtil;

	public ModelObject create() {
		String name = nameTextBoxModel.getText();
		String empleador = empleadorTextBoxModel.isEdited() ? empleadorTextBoxModel.getText() : null;
		String description = descriptionTextBoxModel.getText();
		String contact = contactTextBoxModel.getText();
		Date validUntilDate = validUntilTextBoxModel.isEdited() ? DateUtilImpl.parseDate(validUntilTextBoxModel.getText(), 
				DateUtilImpl.formatterSpanish) : null;
		
		nameTextBoxModel.setHasError(false);
		descriptionTextBoxModel.setHasError(false);
		contactTextBoxModel.setHasError(false);
		
		StringBuffer text = new StringBuffer();
		if(!nameTextBoxModel.isEdited()){
			text.append("ingrese un nombre\n");
			nameTextBoxModel.setHasError(true);
		}
		if(!descriptionTextBoxModel.isEdited()){
			text.append("ingrese una descripcion\n");
			descriptionTextBoxModel.setHasError(true);
		}
		if(!contactTextBoxModel.isEdited()){
			text.append("ingrese un contacto\n");
			contactTextBoxModel.setHasError(true);
		}
		
		
		if(text.length() > 0){
			jsUtil.trackEvent(Constants.CAT_PUBLISHING, Constants.ACT_MSG_SHOWN, text.toString());
			JsUtil.getInstance().showAlert(text.toString());
			return null;
		}

		Job job = new Job();
		if(createObjectModel.getCreateModelObject() != null)
			job = (Job) createObjectModel.getCreateModelObject();
		job.setName(name);
		job.setEmployer(empleador);
		job.setDescription(new Text(description));
		job.setRegisteredDate(new Date());
		job.setContact(contact);
		job.setValidUntilDate(validUntilDate);
		
		return job;
	}

	public void registerContactTextBoxModel(PrefilledTextBoxModel contactTextBoxModel) {
		this.contactTextBoxModel = contactTextBoxModel;
	}

	public void registerCreateObjectModel(CreateObjectModel createObjectModel) {
		this.createObjectModel = createObjectModel;
		createObjectModel.addPropertyChangeListener("createModelObject", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				updateUi();
			}
		});
	}

	public void registerCreateObjectWidget(ILazyWidget createObjectWidget) {
		createObjectWidget.addWidgetListener(new WidgetListenerAdapter() {
			@Override
			public void onAttach(IWidget widget) {
				updateUi();
			}
		});
	}
	
	public void registerDescriptionTextBoxModel(PrefilledTextBoxModel descriptionTextBoxModel) {
		this.descriptionTextBoxModel = descriptionTextBoxModel;
	}

	public void registerEmpleadorTextBoxModel(final SuggestBoxModel empleadorTextBoxModel) {
		this.empleadorTextBoxModel = empleadorTextBoxModel;
		empleadorTextBoxModel.addPropertyChangeListener("hasFocus", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				if(!empleadorTextBoxModel.hasFocus())
					updateImageSearch();
			}
		});
		empleadorTextBoxModel.addPropertyChangeListener("choosenSuggestion", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				SuggestionModel choosenSuggestion = empleadorTextBoxModel.getChoosenSuggestion();
				if(choosenSuggestion != null && !contactTextBoxModel.isEdited()){
					SearchRequestImpl searchRequest = new SearchRequestImpl();
					searchRequest.setLimit(5);
					searchRequest.setClassName(Job.class.getName());
					searchRequest.setText(choosenSuggestion.getSuggestion().getDisplayText());
					searchRequest.setSort(new Sort("registeredDate",false));
					DataService.Util.getInstance().search(searchRequest, new AsyncCallback<SearchResult<Job>>(){
						public void onFailure(Throwable caught) {
							caught.printStackTrace();
						}
						public void onSuccess(SearchResult<Job> result) {
							for (Job job : result.getObjects()) {
								String contact = job.getContact();
								if(!StringUtil.isEmpty(contact)){
									contactTextBoxModel.setText(contact);
									break;
								}
							}
						}
					});
				}
			}
		});
		
	}

	public void registerNameTextBoxModel(final PrefilledTextBoxModel nameTextBoxModel) {
		this.nameTextBoxModel = nameTextBoxModel;
		nameTextBoxModel.addPropertyChangeListener("hasFocus", new PropertyChangeListener(){
			public void propertyChange(PropertyChangeEvent evt) {
				if(!nameTextBoxModel.hasFocus())
					updateImageSearch();
			}
		});
	}

	public void registerValidUntilTextBoxModel(PrefilledTextBoxModel validUntilTextBoxModel) {
		this.validUntilTextBoxModel = validUntilTextBoxModel;
	}

	private void updateImageSearch() {
		StringBuffer imageSearch = new StringBuffer("");

		if(empleadorTextBoxModel.isEdited())
			imageSearch.append(empleadorTextBoxModel.getText()).append(" ");
		else if(nameTextBoxModel.isEdited())
			imageSearch.append(nameTextBoxModel.getText()).append(" ");
		
		createObjectModel.setImageSearch(imageSearch.length() > 0 ? imageSearch.toString() : null);
	}

	private void updateUi() {
		ModelObject object = createObjectModel.getCreateModelObject();
		if(object != null && !(object instanceof Job))
			return;
		Job createModelObject = (Job) createObjectModel.getCreateModelObject();
		descriptionTextBoxModel.setText(createModelObject != null ? createModelObject.getDescription() != null ? createModelObject.getDescription().toString() : null : null);
		nameTextBoxModel.setText(createModelObject != null ? createModelObject.getName() : null);
		empleadorTextBoxModel.setText(createModelObject != null ? createModelObject.getEmployer() : null);
		contactTextBoxModel.setText(createModelObject != null ? createModelObject.getContact() : null);
		validUntilTextBoxModel.setText(createModelObject != null ? 
				DateUtilImpl.getInstance().formatDateSpanish(createModelObject.getValidUntilDate()) : null);
		updateImageSearch();
	}

	public void registerJsUtil(IJsUtil jsUtil) {
		this.jsUtil = jsUtil;
	}
}